﻿/*************************************************
作者: Plane
邮箱: 1785275942@qq.com
功能: 资源加载服务

           ~~获取更多教学资讯~~
//----------------*----------------\\
        教学官网：www.qiqiker.com
        官方微信服务号: qiqikertuts
        Plane老师微信: PlaneZhong
\\----------------*----------------//
*************************************************/

using System;
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.SceneManagement;

public class ResSvc : ILogic {
    //-------------Declaration----------------//
    private readonly Dictionary<string, GameObject> cacheDic = new();
    readonly Dictionary<string, AudioClip> audioDic = new();
    private readonly Dictionary<string, Sprite> spriteDic = new();
    private Action UpdateSceneLoadingProgress;

    //-------------Flow Functions-------------//
    public void Init() {
        this.Log("Init ResSvc Done.");
    }
    public void Tick() {
        UpdateSceneLoadingProgress?.Invoke();
    }
    public void UnInit() {
        this.Log("UnInit ResSvc.");
    }

    //-------------Core Functions-------------//
    public void LoadSceneAsync(string sceneName, Action<float> loadingProgress, Action loadDone) {
        if (sceneName == SceneManager.GetActiveScene().name) {
            loadingProgress?.Invoke(1);
            loadDone?.Invoke();
        }
        else {
            AsyncOperation ao = SceneManager.LoadSceneAsync(sceneName);
            UpdateSceneLoadingProgress = () => {
                loadingProgress?.Invoke(ao.progress);
                if (ao.progress == 1.0f) {
                    loadDone?.Invoke();
                    UpdateSceneLoadingProgress = null;
                    ao = null;
                }
            };
        }
    }
    public GameObject LoadPrefab(string path, bool cache = false) {
        if (!cacheDic.TryGetValue(path, out GameObject go)) {
            go = Resources.Load<GameObject>(path);
            if (cache) {
                cacheDic.Add(path, go);
            }
        }

        GameObject prefab = null;
        if (go != null) {
            prefab = UnityEngine.Object.Instantiate(go);
        }
        return prefab;
    }
    public AudioClip LoadAudio(string path, bool cache) {
        if (!audioDic.TryGetValue(path, out AudioClip au)) {
            au = Resources.Load<AudioClip>(path);
            if (cache) {
                audioDic.Add(path, au);
            }
        }
        return au;
    }
    public Sprite LoadSprite(string path, bool cache = false) {
        if (!spriteDic.TryGetValue(path, out Sprite sp)) {
            sp = Resources.Load<Sprite>(path);
            if (cache) {
                spriteDic.Add(path, sp);
            }
        }
        return sp;
    }
}